package com.open.center.jpa.annotation;

import java.lang.reflect.Member;
import java.util.UUID;

import com.github.f4b6a3.uuid.UuidCreator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.generator.AnnotationBasedGenerator;
import org.hibernate.generator.GeneratorCreationContext;
import org.hibernate.id.IdentifierGenerator;

/**
 * 自定义UUID生成方式
 *
 * @author Riche's
 * @since 2025/8/26
 */
@Slf4j
@Data
public class MeUuidGenerator implements IdentifierGenerator, AnnotationBasedGenerator<MeUuid> {

    private UuidVersion uuidVersion = UuidVersion.V7;

    private boolean useUpper = false;

    @Override
    public void initialize(MeUuid meUuid, Member member, GeneratorCreationContext generatorCreationContext) {
        this.uuidVersion = meUuid.version();
        this.useUpper = meUuid.useUpper();
    }

    @Override
    public Object generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) {
        UUID uuid;
        switch (uuidVersion) {
            case UuidVersion.V6 -> uuid = UuidCreator.getTimeOrdered();
            case UuidVersion.V4 -> uuid = UuidCreator.getRandomBased();
            case UuidVersion.V1 -> uuid = UuidCreator.getTimeBased();
            default -> uuid = UuidCreator.getTimeOrderedEpoch();
        }
        return useUpper ? uuid.toString().toUpperCase() : uuid.toString();
    }

    @Override
    public void initialize(SqlStringGenerationContext context) {
        IdentifierGenerator.super.initialize(context);
    }
}
